package com.gin.kotlin.no_gay_alliance.fragment.topiclist

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.view.MenuProvider
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.TopicListActivity
import com.gin.kotlin.no_gay_alliance.activity.TopicListActivity.Companion.KEY_ARGUMENT
import com.gin.kotlin.no_gay_alliance.adapter.SearchAreaAdapter
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument.Type
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.databinding.EditTextKeywordBinding
import com.gin.kotlin.no_gay_alliance.databinding.FragmentTopicListTopicSearchBinding
import com.gin.kotlin.no_gay_alliance.model.SearchAreaModel
import com.gin.nga.enums.param.SearchContent

/**
 * 版面搜索和合集搜索
 */
open class TopicSearchFragment : AbstractTopicListFragment<FragmentTopicListTopicSearchBinding>(), MenuProvider, TextView.OnEditorActionListener {

    /**
     * 顶部标题栏组件
     */
    private var toolbar: Toolbar? = null

    /**
     * 关键字输入框
     */
    private lateinit var editText: EditText

    override fun onCreateView() {
        // 先不装载适配器

        // 创建一个 EditText放入Toolbar
        val toolbar = (requireActivity() as? TopicListActivity)?.toolbar ?: throw RuntimeException("未找到Toolbar")
        this.toolbar = toolbar
        this.editText = EditTextKeywordBinding.inflate(layoutInflater).root
        this.editText.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        this.editText.setOnEditorActionListener(this)
        this.editText.requestFocus()
        InputMethodUtils.show(this.editText, requireContext())

        // 修改时联动修改参数
        this.editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                argument = argument.copy(keyword = s.toString())
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        toolbar.addView(editText)

        val b = this.b ?: return

        // 搜索区域
        b.rvSearchArea.adapter = SearchAreaAdapter(
            requireContext(),
            handler!!,
            this.argument.searchAreas?.toMutableList() ?: mutableListOf()
        )
        // 搜索正文和仅精华
        b.swSearchRecommend.setOnCheckedChangeListener { _, isChecked -> this.argument = this.argument.copy(recommendOnly = isChecked) }

        b.radioGroupSearchContent.also { rg ->
            rg.check(
                when (this.argument.searchContent) {
                    SearchContent.TOPIC_CONTENT -> R.id.radio_button_search_topic_content
                    SearchContent.REPLY_CONTENT -> R.id.radio_button_search_reply_content
                    null -> R.id.radio_button_search_title
                }
            )

            rg.setOnCheckedChangeListener { _, checkedId ->
                this.argument = this.argument.copy(
                    searchContent = when (checkedId) {
                        R.id.radio_button_search_topic_content -> SearchContent.TOPIC_CONTENT
                        R.id.radio_button_search_reply_content -> SearchContent.REPLY_CONTENT
                        else -> null
                    }
                )
            }

        }
    }


    override fun onResume() {
        super.onResume()
        this.toolbar?.title = null

    }

    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        // 搜索
        menuInflater.inflate(R.menu.search, menu)
        // 过滤
        menuInflater.inflate(R.menu.filter, menu)
    }

    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return when (menuItem.itemId) {
            R.id.mi_search -> {
                doSearch()
                true

            }
            // 切换选项显示状态
            R.id.mi_filter -> {
                b?.linearLayoutTopMenu?.visibility = if (b?.linearLayoutTopMenu?.visibility == View.VISIBLE) View.GONE else View.VISIBLE
                true

            }

            else -> false
        }
    }

    private fun doSearch() {
        InputMethodUtils.hide(this.editText, requireContext())

        if (this.argument.keyword.isNullOrEmpty()) {
            toast(getString(R.string.edit_text_hint_please_enter_keyword))
            return
        }
        // 合集搜索
        if (this.argument.type == Type.COL_SEARCH && this.argument.colTid == null) {
            val searchAreas = this.argument.searchAreas
            if (searchAreas.isNullOrEmpty()) {
                toast(getString(R.string.toast_message_select_search_area))
                return
            } else {
                this.argument = this.argument.copy(colTid = searchAreas[0].entryId)
            }
        }
        // 版面搜索
        if (this.argument.type == Type.FORUM_SEARCH) {
            val searchAreas = this.argument.searchAreas
            // 如果搜索区域为空(从url加载)，要求预先填写fid
            if (searchAreas.isNullOrEmpty()) {
                if (this.argument.forumIds.isNullOrEmpty()) {
                    toast(getString(R.string.toast_message_select_search_area))
                }
            } else {
                // 如果搜索区域不为空，要求选择至少一个区域， fid从搜索区域中获取
                val checked = searchAreas.filter { it.checked }
                if (checked.isEmpty()) {
                    toast(getString(R.string.toast_message_select_search_area))
                } else {
                    this.argument = this.argument.copy(forumIds = checked.map { it.entryId })
                }
            }
        }

        Log.i(TAG, "执行搜索: ${mapper.writeValueAsString(this.argument)}")

        // 隐藏选项
        b?.linearLayoutTopMenu?.visibility = View.GONE

        // 装载适配器
        b?.viewPager2?.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = totalPage
            override fun createFragment(position: Int) = TopicPageFragment.newInstance(argument.copy(page = position + 1))
        }
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        // 当按下软键盘搜索键时，执行搜索
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 执行搜索
            doSearch()
            return true
        }
        return false
    }

    companion object {

        fun newInstance(argument: TopicListArgument) = TopicSearchFragment()
            .also { it.arguments = Bundle().also { b -> b.putParcelable(KEY_ARGUMENT, argument) } }

        /**
         * 启动活动：版面搜索
         */
        fun startActivityForum(
            context: Context,
            searchAreas: List<SearchAreaModel>,
            keyword: String? = null,
            forumIds: List<Long>? = null,
            page: Int? = null,
            searchContent: SearchContent? = null,
            recommendOnly: Boolean? = null,
        ) = TopicListActivity.startActivity(
            context, TopicListArgument(
                Type.FORUM_SEARCH,
                searchAreas = searchAreas,
                keyword = keyword,
                /**
                 * 如果区域只有1个，直接作为区域
                 */
                forumIds = forumIds,
                page = page,
                searchContent = searchContent,
                recommendOnly = recommendOnly,
            )
        )

        /**
         * 启动活动：合集搜索
         */
        fun startActivityCol(
            context: Context,
            searchAreas: List<SearchAreaModel>,
            keyword: String? = null,
            colTid: Long? = null,
            page: Int? = null,
            searchContent: SearchContent? = null,
            recommendOnly: Boolean? = null,
        ) = TopicListActivity.startActivity(
            context, TopicListArgument(
                Type.COL_SEARCH,
                searchAreas = searchAreas,
                keyword = keyword,
                colTid = colTid,
                page = page,
                searchContent = searchContent,
                recommendOnly = recommendOnly,
            )
        )
    }
}